﻿#include "CenterWidget.h"
#include <iostream>
#include <fstream>
#include <QHBoxLayout>
#include <QStandardItemModel>
#include <QLabel>
#include <QVBoxLayout>
#include <QHeaderView>

#include "ElaPushButton.h"
#include "ElaScrollPageArea.h"
#include "ElaTabWidget.h"
#include "ElaTabBar.h"
#include "ElaScrollBar.h"
#include "ElaTreeView.h"
#include "ElaText.h"
#include "qcustomplot.h"
#include "ElaTheme.h"
#include "ElaTableView.h"
#include "T_FinalReportTableViewModel.h"
#include "globalenums.h"
#include "ReportPreviewDisplay.h"
#include "GenerateReportBase.h"
#include "FinalReportData.h"
#include "RealTimeMonitor.h"
#include "mainWindow.h"
#include "ElaMessageBar.h"
#include "T_CloseReportWarningWidget.h"
#include "insertScreenshotIntoReport.h"

using namespace std;
namespace GenerateReport
{

    CenterWidget::CenterWidget(QWidget* parent)
        : T_BasePage(parent)
    {
        // 设置窗口布局
        setContentsMargins(9, 9, 9, 9);
        QWidget* centralWidget = new QWidget(this);
        QHBoxLayout* centerVLayout = new QHBoxLayout(centralWidget);
        centerVLayout->setContentsMargins(0, 0, 0, 0);
        centerVLayout->setSpacing(5);

        // ElaTabWidget
        m_tabWidget = new ElaTabWidget(this);
        centerVLayout->addWidget(m_tabWidget);
        addCentralWidget(centralWidget, true, false, 0);

        //ElaTableView
        m_tableView = new ElaTableView(this);
        m_tableView->verticalHeader()->hide();
        m_tableView->horizontalHeader()->hide();
        m_tableView->setRowHeight(0, 20);
        m_tableView->setRowHeight(1, 20);
        m_tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
        m_tableView->hide();
        m_tableView->setMouseTracking(true); // 设置鼠标追踪

        disconnect(m_tabWidget->tabBar(), &ElaTabBar::tabCloseRequested, 0, 0);
        connect(m_tabWidget->tabBar(), &ElaTabBar::tabCloseRequested, this, &CenterWidget::on_tabWidget_tabCloseRequested);
        connect(m_tableView, &ElaTableView::entered, this, &CenterWidget::on_tabView_doMouseTrackTip);
        connect(m_tableView, &ElaTableView::doubleClicked, this, &CenterWidget::on_tableView_doubleClicked);
    }

    CenterWidget::~CenterWidget()
    {
        //std::cout << "~CenterWidget()" << std::endl;
        if(m_widget)
        {
            delete m_widget;
            m_widget = nullptr;
        }
        if (m_noDataDisplayPage)
        {
            delete m_noDataDisplayPage;
            m_noDataDisplayPage = nullptr;
        }
        if (m_tableView)
        {
            delete m_tableView;
            m_tableView = nullptr;
        }
        if (m_tabWidget)
        {
            delete m_tabWidget;
            m_tabWidget = nullptr;
        }
    }
    void CenterWidget::addReportRelatedSubWidget(GenerateReport::ReportRelatedSubWidgetType type, QPair<qint64, qint64> indexPair, QString reportName)
    {
        if (type == GenerateReport::ReportRelatedSubWidgetType::CreateNewReportSubWidget)
        {
            //窗口打开时，开启定时保存定时器
            _monitor = new RealTimeMonitor;
            _monitor->setTimeStep(300000);//5min
            _monitor->run();
            
            auto childWin = QWindow::fromWinId(WId(indexPair.first));
            m_widget = QWidget::createWindowContainer(childWin, m_tabWidget, Qt::Widget);
            m_tabWidget->addTab(m_widget, QStringLiteral("新建报告"));
            m_tabWidget->setCurrentWidget(m_widget);
            if (GenerateReportBaseInstance->getCreateAndScreenshotToReport())
            {
                GenerateReport::insertScreenshotIntoReport insertImage;
                insertImage.actionSlot_insertScreenshotIntoReport();
                GenerateReportBaseInstance->setCreateAndScreenshotToReport(false);
            }
            //报告窗口打开后，设置创建报告按钮禁用
            GenerateReportBaseInstance->getMainWindow()->toolButtonCreateNewReportStateUpdate(false);
        }
        else if (type == GenerateReport::ReportRelatedSubWidgetType::ReportPreviewDisplaySubWidget)
        {
            auto childWin = QWindow::fromWinId(WId(indexPair.first));
            auto _qWidget = QWidget::createWindowContainer(childWin, m_tabWidget, Qt::Widget);
            m_tabWidget->addTab(_qWidget, reportName);
            m_tabWidget->setCurrentWidget(_qWidget);
            auto _previewDisplatWidgetIndex = m_tabWidget->indexOf(_qWidget);
            if (!m_docWidgetMap.contains(_previewDisplatWidgetIndex))
            {
                m_docWidgetMap.insert(_previewDisplatWidgetIndex, indexPair.second);
            }
            GenerateReportBaseInstance->appendDisplayReportWidget(reportName, _qWidget);
        }
        else if (type == GenerateReport::ReportRelatedSubWidgetType::ReportRecordFormSubWidget)
        {
            if (FinalReportDataInstance->getFinalReportCount())
            {
                //删除“暂无数据”展示页
                auto _pageIndex = m_tabWidget->indexOf(m_noDataDisplayPage);
                if (-1 != _pageIndex)
                {
                    m_tabWidget->removeTab(_pageIndex);
                }

                //报告记录窗口不存在则新建窗口
                //报告窗口存在则设置为当前窗口         
                auto _index = m_tabWidget->indexOf(m_tableView);
                if (_index == -1)
                {
                    m_tableView->setModel(new T_FinalReportTableViewModel(this));
                    m_tabWidget->addTab(m_tableView, QStringLiteral("报告列表"));
                    m_tabWidget->setCurrentWidget(m_tableView);
                    //报告记录窗口打开后，设置创建报告按钮禁用
                    GenerateReportBaseInstance->getMainWindow()->toolButtonReportRecordFormStateUpdate(false);
                }
                else
                {
                    //需刷新列表窗口内容
                    UpdateReportRecordContent();
                }
            }
            else
            {
                m_noDataDisplayPage = new QLabel(QStringLiteral("暂无数据"), this);
                m_noDataDisplayPage->setAlignment(Qt::AlignCenter);
                QFont font = m_noDataDisplayPage->font();
                font.setPixelSize(32);
                m_noDataDisplayPage->setFont(font);
                m_tabWidget->addTab(m_noDataDisplayPage, QStringLiteral("报告列表"));
                GenerateReportBaseInstance->getMainWindow()->toolButtonReportRecordFormStateUpdate(false);
            }
        }
        else
        {
            return;
        }
    }

    void CenterWidget::UpdateReportRecordContent()
    {
        m_tableView->setModel(new T_FinalReportTableViewModel(this));
        m_tabWidget->setCurrentWidget(m_tableView);
    }

    void CenterWidget::on_tabWidget_tabCloseRequested(int index)
    {
        //如果关闭报告的窗口，则需判断是否需要保存
        auto _reportWidgetIndex = m_tabWidget->indexOf(m_widget);
        auto _tableViewWidgetIndex = m_tabWidget->indexOf(m_tableView);
        auto _noDataDisplayPageIndex = m_tabWidget->indexOf(m_noDataDisplayPage);
        if (index == _reportWidgetIndex)
        {
            //弹窗提示未保存
            m_closeReportWarningWidget = new T_CloseReportWarningWidget();

            m_closeReportWarningWidget->hide();
            m_closeReportWarningWidget->setFixedSize(400, 200);
            m_closeReportWarningWidget->moveToCenter();
            m_closeReportWarningWidget->show();
        }
        else if (index == _tableViewWidgetIndex)
        {
            m_tabWidget->removeTab(index);
            //报告记录窗口关闭后，设置创建报告按钮可用
            GenerateReportBaseInstance->getMainWindow()->toolButtonReportRecordFormStateUpdate(true);
        }
        else if (index == _noDataDisplayPageIndex)
        {
            m_tabWidget->removeTab(index);
            GenerateReportBaseInstance->getMainWindow()->toolButtonReportRecordFormStateUpdate(true);
        }
        else
        {
            auto _displayWidgetMap = GenerateReportBaseInstance->getDisplayReportWidgetMap();
            for (auto _it = _displayWidgetMap.begin(); _it != _displayWidgetMap.end(); _it++)
            {
                auto _index = m_tabWidget->indexOf(_it.value());
                if (index == _index)
                {
                    m_tabWidget->removeTab(index);
                    GenerateReportBaseInstance->removeDisplayReportWidget(_it.key());
                    delete _it.value();
                    _it.value() = nullptr;
                    break;
                }
            }
            if (m_docWidgetMap.contains(index))
            {
                GenerateReportBaseInstance->removeDocWindow(m_docWidgetMap.value(index));
                m_docWidgetMap.remove(index);
            }

        }
    }

    void CenterWidget::on_tabView_doMouseTrackTip(const QModelIndex& index)
    {
        //std::cout << "---on_tabView_doMouseTrackTip ---" << std::endl;
        //std::cout << "---index.row ---" << index.row() << std::endl;
        //std::cout << "---index.column ---" << index.column() << std::endl;
        //yr-临时方案
        auto _finalReportData = FinalReportDataInstance->getFinalReportTotalData();
        auto _isExist = _finalReportData.at(index.row()).at(3);
        if (_isExist == "false")
            QToolTip::showText(QCursor::pos(), QStringLiteral("文档已不存在"));
        else
            QToolTip::showText(QCursor::pos(), QStringLiteral("双击显示文档详情"));

        //yr-需将“点击进入详情”显示到中间单元格
        //m_tableView->model()->setData(index, QString("点击进入详情"));
        //m_tableView->update();
    }

    void CenterWidget::on_tableView_doubleClicked(const QModelIndex& index)
    {
        //std::cout << "---on_tableView_doubleClicked ---"<< std::endl;
        //std::cout << "---index.row ---" << index.row() << std::endl;
        //std::cout << "---index.column ---" << index.column() << std::endl;
      
        auto _finalReportTotalData = FinalReportDataInstance->getFinalReportTotalData();
        auto _sigleReportInfoList = _finalReportTotalData.at(index.row());
        auto _DisplayReportName = _sigleReportInfoList.at(0);
        auto _DisplayReportFilePath = _sigleReportInfoList.at(1);
        //检测是否有同名文档在打开状态，如果有则提示关闭
        std::ifstream file(_DisplayReportFilePath.toStdString(), std::ios::in);
        if (file.is_open())//检测有没有被其他软件打开
        {
            file.close();
            //判断文档是否已在本软件打开，已打开则切换
            auto _displayWidgetMap = GenerateReportBaseInstance->getDisplayReportWidgetMap();
            if (_displayWidgetMap.contains(_DisplayReportName))
            {
                auto _displayWidget = _displayWidgetMap.value(_DisplayReportName);
                m_tabWidget->setCurrentWidget(_displayWidget);
            }
            else
            {
                GenerateReport::ReportPreviewDisplay* _rpd = new GenerateReport::ReportPreviewDisplay;
                _rpd->actionSlot_ReportPreviewDisplay(index.row());
            }
        }
        else
        {
            ElaMessageBar::error(ElaMessageBarType::PositionPolicy::Top, "打开失败", QStringLiteral("文档已在其他软件中打开，请先关闭文档"), 3000, GenerateReport::GenerateReportBase::getinstance()->getMainWindow());
            return;
        }
    }

    void CenterWidget::closeCurrentReportWidget()
    {
        //窗口移除时，关闭定时保存定时器
        _monitor->stop();
        auto _reportWidgetIndex = m_tabWidget->indexOf(m_widget);
        m_tabWidget->removeTab(_reportWidgetIndex);
        if (_monitor != nullptr) delete _monitor;
        //报告窗口关闭后，设置创建报告按钮可用
        GenerateReportBaseInstance->getMainWindow()->toolButtonCreateNewReportStateUpdate(true);
        UpdateReportRecordContent();
    }

}
